using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
	#region Properties
	public JoyStick _moveJoystick;
	public PlayerStats _playerStats;
	//In degree
	public int _rotationDelta = 60;
	//In degree
	public int _rotationSpeed = 1;
	#endregion
	
	#region Fields
	private Transform _transform = null;
	#endregion
	// Use this for initialization
	void Start () {
		//Cache transform vector -> improve performance
		_transform = transform;
	}
	
	// Update is called once per frame
	void Update () {
		//Translation
		Vector3 moveDirection = new Vector3(_moveJoystick.position.x, _moveJoystick.position.y,0);
		_transform.localPosition += moveDirection.normalized * _playerStats.Speed * Time.deltaTime;
		
		//Rotation
		if (_moveJoystick.position.x != 0){
			if (_moveJoystick.position.x > 0.5){
				rotateRight();
			}
			else if (_moveJoystick.position.x < -0.5){
				rotateLeft();
			}
			else{
				rotateZero();
			}
		}
		else{
			rotateZero();
		}
	}
	
	/// <summary>
	///Rotate left 
	/// </summary>
	private void rotateLeft ()
	{
		//Stop rotating when threshold is reached
		if (_transform.eulerAngles.y <= 180 && _transform.eulerAngles.y >= _rotationDelta)
			return;
		_transform.eulerAngles += new Vector3 (0f, _rotationSpeed * Time.deltaTime, 0f);
	}

	/// <summary>
	///Rotate right 
	/// </summary>
	private void rotateRight ()
	{
		//Stop rotating when threshold is reached
		if (_transform.eulerAngles.y >= 180 && _transform.eulerAngles.y <= 360 - _rotationDelta)
			return;
		_transform.eulerAngles += new Vector3 (0f, -_rotationSpeed * Time.deltaTime, 0f);
	}

	/// <summary>
	///Rotate the ship back to origin 
	/// </summary>
	private void rotateZero ()
	{
		//Rotated right, now rotating left
		if (_transform.eulerAngles.y >= 180 && _transform.eulerAngles.y <= 360) {
			_transform.eulerAngles += new Vector3 (0f, _rotationSpeed * Time.deltaTime, 0f);
		}
		//Rotated left, now rotating right
		if (_transform.eulerAngles.y <= 180 && _transform.eulerAngles.y >= 0) {
			_transform.eulerAngles += new Vector3 (0f, -_rotationSpeed * Time.deltaTime, 0f);
		}
	}
}
